#include "IndexGenerator.h"

#include "Utility.h"

#include "config.h"

#include <stdio.h>
#include <stdlib.h>

struct indexItem
{
    int key;
    int number;
};
int compare (const void * a, const void * b)
{
    return ( ((indexItem*)a)->key - ((indexItem*)b)->key );
}

void generateIndex(char* RelationName, int maxLenght, bool printText)
{
    FILE* fileBin = 
        fopen(getFileNameByRelationNameWithExtension(RelationName,"bin"),"rb");

    indexItem* keys = new indexItem[maxLenght];

    fseek(fileBin, sizeof(int)*INDEX_ATTR, SEEK_SET);

    int tmp = 0;
    int count = 0;
    int nBytes = 0;
    while((nBytes = fread(&tmp,sizeof(int),1,fileBin)) > 0)
    {
        keys[count].key = tmp;
        keys[count].number = count;
        fseek(fileBin, sizeof(int)*(ARITY-1), SEEK_CUR);   
        count++;
    }

    fclose(fileBin);

    qsort (keys, count, sizeof(indexItem), compare);

    FILE* fileText = NULL;
    if (printText) fileText = 
        fopen(getPrefixedFileNameByRelationNameWithExtension(RelationName,"I","txt"),"w");

    fileBin = 
        fopen(getPrefixedFileNameByRelationNameWithExtension(RelationName,"I","bin"),"wb");

    for(int i = 0; i < count; i++)
    {
        fwrite(&keys[i].key,sizeof(int),1,fileBin);
        fwrite(&keys[i].number,sizeof(int),1,fileBin);

        if(printText) fprintf(fileText,"%d %d\n",keys[i].key,keys[i].number);
    }

    delete[] keys;

    if (printText) fclose(fileText);

    fclose(fileBin);
}